package com.flyone.fuxiao.utils;

import com.flyone.fuxiao.constant.FileConstant;
import com.flyone.fuxiao.model.res.StartFireResponse;
import okhttp3.HttpUrl;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 星火模型 调用
 *
 * @author flyone
 * @date 2024/3/9
 */
@Component
public class ImageUtils {

    @Resource
    private QiniuUtils qiniuUtils;

    /**
     * 1.发起post请求
     */
    public String doPostJson(String url, Map<String, String> urlParams, String json) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        CloseableHttpResponse closeableHttpResponse = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            String asciiUrl = URI.create(url).toASCIIString();
            RequestBuilder builder = RequestBuilder.post(asciiUrl);
            builder.setCharset(StandardCharsets.UTF_8);
            if (urlParams != null) {
                for (Map.Entry<String, String> entry : urlParams.entrySet()) {
                    builder.addParameter(entry.getKey(), entry.getValue());
                }
            }
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            builder.setEntity(entity);
            HttpUriRequest request = builder.build();
            // 执行http请求
            closeableHttpResponse = closeableHttpClient.execute(request);
            resultString = EntityUtils.toString(closeableHttpResponse.getEntity(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 星火模型鉴权方法*
     * @param hostUrl
     * @param apiKey
     * @param apiSecret
     * @return
     * @throws Exception
     */
    public String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // date="Thu, 12 Oct 2023 03:05:28 GMT";
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" + "date: " + date + "\n" + "POST " + url.getPath()
                + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format(
                "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",
                apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath()))
                .newBuilder()
                .//
                        addQueryParameter("authorization",
                        Base64.getEncoder().encodeToString(
                                authorization.getBytes(StandardCharsets.UTF_8)))
                .//
                        addQueryParameter("date", date).//
                        addQueryParameter("host", url.getHost()).//
                        build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }

    /**
     * 上传七牛云*
     * @param startFireResponse
     * @return
     */
    public String getImage(StartFireResponse startFireResponse) {
        String base64Data = startFireResponse.getPayload().getChoices().getText().get(0).getContent();

        // 解码Base64数据
        byte[] imageBytes = Base64.getDecoder().decode(base64Data);
        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String filename = uuid + "-" + startFireResponse.getHeader().getSid() + ".png";
        boolean result = qiniuUtils.uploadByBytes(imageBytes, filename);
        if (result) {
            // 返回可访问地址
            return FileConstant.QINIU_HOST + filename;
        }
        return "上传失败";
    }

    /**
     * 上传七牛云*
     * @param base64Data base64数据
     * @param filePath   文件地址
     * @return 图片URL
     */
    public String getImageBytes(String base64Data, String filePath) {
        // 解码Base64数据
        byte[] imageBytes = Base64.getDecoder().decode(base64Data);
        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String filename = uuid + "-" + filePath + ".png";
        boolean result = qiniuUtils.uploadByBytes(imageBytes, filename);
        if (result) {
            // 返回可访问地址
            return FileConstant.QINIU_HOST + filename;
        }
        return "上传失败";
    }
}